package run

import (
	"context"
	"github.com/zeebo/errs"
	"golang.org/x/sync/errgroup"
)

type Run interface {
	Run(ctx context.Context) error
}

type Group struct {
	items []Run
}

func NewGroup() *Group {
	return &Group{items: make([]Run, 0)}
}

func (g *Group) Add(r Run) {
	g.items = append(g.items, r)
}

func (g *Group) Run(ctx context.Context) error {
	var group errgroup.Group
	es := errs.Group{}
	for i := range g.items {
		func(i int) {
			group.Go(func() error {
				_err := g.items[i].Run(ctx)
				es.Add(_err)
				return _err
			})
		}(i)
	}
	return errs.Combine(group.Wait(), es.Err())
}
